<template>
  <div class="copywritingList" copywritingList>
    <!-- <div class="title pl20 pr14">
      <div class="title-left">商品管理（分总管理）</div>
    </div> -->
    <div class="search-box-new pb10">
      <div class="pr12">搜索： <a-input placeholder="产品ID/产品名称/产品经理" style="width: 280px" v-model="search.keywords" @pressEnter="handlesearch" /></div>
      <div>
        站点：
        <a-select
          showSearch
          :defaultActiveFirstOption="false"
          :filterOption="false"
          style="width:150px;"
          @search="getAllStation($event)"
          @change="handleChange"
          :notFoundContent="null"
          v-model="search.locationId"
          placeholder="请选择站点"
          class="filter-select"
        >
          <a-select-option v-for="item in allStation" :key="item.id" :value="item.id">{{ item.city }} </a-select-option>
        </a-select>
      </div>
      <div class="pl20 pr20">
        产品类型：
        <a-select style="width: 120px" @change="handleChange" v-model="search.productType">
          <a-select-option :value="null">
            全部
          </a-select-option>
          <a-select-option :value="0">
            周边游
          </a-select-option>
          <a-select-option :value="1">
            酒景
          </a-select-option>
          <a-select-option :value="2">
            亦鲜生
          </a-select-option>
          <a-select-option :value="3">
            只上线抖音
          </a-select-option>
        </a-select>
      </div>
      <div>
        产品状态：
        <a-select style="width: 120px" @change="handleChange" v-model="search.productStatus">
          <a-select-option :value="-2">
            全部
          </a-select-option>
          <a-select-option :value="-1">
            已作废
          </a-select-option>
          <a-select-option :value="0">
            待完成
          </a-select-option>
          <a-select-option :value="1">
            待派单
          </a-select-option>
          <a-select-option :value="2">
            已派文案
          </a-select-option>
          <a-select-option :value="3">
            已派设计师
          </a-select-option>
          <a-select-option :value="4">
            待上架确认
          </a-select-option>
          <a-select-option :value="5">
            待上架
          </a-select-option>
          <a-select-option :value="6">
            已上架
          </a-select-option>
          <a-select-option :value="7">
            已下架
          </a-select-option>
        </a-select>
      </div>
      <div>
        上架渠道：
        <a-select style="width: 120px" @change="handleChange" v-model="search.onlineChannel">
          <!-- <a-select-option :value="null">
            全部
          </a-select-option> -->
          <a-select-option :value="1">
            周边游公众号商城
          </a-select-option>
          <a-select-option :value="2">
            周边游APP
          </a-select-option>
          <a-select-option :value="3">
            微信小程序
          </a-select-option>
          <a-select-option :value="4">
            抖音小程序
          </a-select-option>
          <a-select-option :value="5">
            快手小程序
          </a-select-option>
          <a-select-option :value="6">
            百度小程序
          </a-select-option>
          <a-select-option :value="7">
            渠道商城
          </a-select-option>
        </a-select>
      </div>
      <div class="search-box-btn">
        <a-button class="reset-btn" @click="reset">重置</a-button>
        <a-button @click="handlesearch" type="primary">筛选</a-button>
        <!-- <a-button @click="addProduct" type="primary">发布新商品</a-button> -->
      </div>
    </div>
    <div class="main-body ">
      <a-table :columns="columns" :data-source="data" :loading="loading" :pagination="pagination" @change="paginationChange" :scroll="{ x: 500, y: tableHeight }">
        <template slot="locationName" slot-scope="text">
          <div class="ml14">
            {{ text }}
          </div>
        </template>
        <template slot="name" slot-scope="text, record">
          <div class="product-info pl14">
            <div class="mr10"><img :src="record.faceImg" alt="" /></div>
            <div>
              <div>{{ text }}</div>
              <div>产品ID：{{ record.id }}</div>
              <div>类型：{{ record.productType }}</div>
              <div>发码：{{ record.thirdName }}</div>
            </div>
          </div>
        </template>
        <template slot="pmName" slot-scope="text, record">
          <div v-if="record.pmName">
            产品经理：{{ record.pmName | handleData }}/{{ record.pmPhone | handleData }}
            <!-- /{{ pmCompanyName }} -->
            <a-tag v-if="record.pmStatus === 3">
              已离职
            </a-tag>
          </div>
          <div v-if="record.editUserName">
            文案人员：{{ record.editUserName | handleData }}/{{ record.editPhone | handleData }}
            <a-tag v-if="record.editStatus === 3">
              已离职
            </a-tag>
          </div>
          <div v-if="record.designer">
            设计人员：{{ record.designer | handleData }}/{{ record.designerPhone | handleData }}
            <a-tag v-if="record.designerStatus === 3">
              已离职
            </a-tag>
          </div>
        </template>

        <template slot="contractName" slot-scope="text, record">
          <div class="product-info pl14">
            <div>
              <div>合同ID：{{ record.contractId }}</div>
              <div>名称：{{ record.contractName }}</div>
              <div>结算：{{ record.contractPayTypeStr }}</div>
              <div>状态：{{ record.contractStatusStr }}</div>
            </div>
          </div>
        </template>
        <template slot="subTitle" slot-scope="text, record">
          <div v-if="record.productItems.length > 0" class="pl14">
            <div v-for="(item, i) in record.productItems" :key="i" class="item-br item-no-pl">
              <div class="item-nothing" :title="item.subTitle">
                {{ item.subTitle }}
              </div>
            </div>
          </div>
          <div v-else class="item-br item-nothing">无</div>
        </template>
        <template slot="superFirstMoney" slot-scope="text, record">
          <div v-if="record.productItems.length > 0">
            <div v-for="(item, i) in record.productItems" :key="i" class="item-br">
              <div v-if="record.preReleasedChannels.chosenMainlineChannelCodeList && record.preReleasedChannels.chosenMainlineChannelCodeList.length">
                <span>大/中/小</span> <span style="display: block;">{{ item.superFirstMoney || '0' }}/{{ item.firstMoney || '0' }}/{{ item.secondMoney || '0' }}</span>
              </div>
              <div v-else>
                <div class="pt13 pb17">
                  <div v-if="record.preReleasedChannels.chosenNewMediaChannelCodeList && Array.isArray(record.preReleasedChannels.chosenNewMediaChannelCodeList)">
                    <div v-if="record.preReleasedChannels.chosenNewMediaChannelCodeList.length === 2">
                      <span>抖音/快手：¥ {{ item.tiktokInfo && item.tiktokInfo.channelMoney }}/¥{{ item.kuaiShouInfo && item.kuaiShouInfo.channelMoney }}</span>
                    </div>
                    <div v-else-if="record.preReleasedChannels.chosenNewMediaChannelCodeList.includes('tiktok')">
                      <span>抖音：¥ {{ item.tiktokInfo && item.tiktokInfo.channelMoney }}</span>
                    </div>
                    <div v-else-if="record.preReleasedChannels.chosenNewMediaChannelCodeList.includes('kuaiShou')">
                      <span>快手：¥ {{ item.tiktokInfo && item.tiktokInfo.channelMoney }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="item-br item-nothing">无</div>
        </template>
        <template slot="salePrice" slot-scope="text, record">
          <div v-if="record.productItems.length > 0">
            <div v-for="(item, i) in record.productItems" :key="i" class="item-br">
              <div v-if="record.preReleasedChannels.chosenMainlineChannelCodeList && record.preReleasedChannels.chosenMainlineChannelCodeList.length">
                <span class="del-line">原价：{{ item.originPrice }}</span>
                <span style="display: block;">售价：{{ item.salePrice }}</span>
                <span style="display: block;">结算：{{ item.settlePrice }}</span>
              </div>
              <div v-else>
                <div v-if="record.preReleasedChannels.chosenNewMediaChannelCodeList && Array.isArray(record.preReleasedChannels.chosenNewMediaChannelCodeList)">
                  <div class="pt3 pb7" v-if="record.preReleasedChannels.chosenNewMediaChannelCodeList.includes('tiktok') && item.tiktokInfo">
                    <span style="display: block;">抖音售价：{{ item.tiktokInfo.salePrice }}</span>
                    <span class="del-line">抖音原价：{{ item.tiktokInfo.originPrice }}</span>
                  </div>
                  <div class="pt3 pb7" v-if="record.preReleasedChannels.chosenNewMediaChannelCodeList.includes('tiktok') && item.kuaiShouInfo">
                    <span style="display: block;">快手售价：{{ item.kuaiShouInfo.salePrice }}</span>
                    <span class="del-line">快手原价：{{ item.kuaiShouInfo.originPrice }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="item-br item-nothing">无</div>
        </template>
        <template slot="codeAmount" slot-scope="text, record">
          <div v-if="record.productItems.length > 0">
            <div v-for="(item, i) in record.productItems" :key="i" class="item-br">
              <div class="item-nothing">
                {{ item.codeAmount }}
              </div>
            </div>
          </div>
          <div v-else class="item-br item-nothing">无</div>
        </template>

        <template slot="zeroReplaceAmount" slot-scope="text, record">
          <div v-if="record.productItems.length > 0">
            <div v-for="(item, i) in record.productItems" :key="i" class="item-br ">
              <div class="item-nothing">
                {{ item.zeroReplaceAmount }}
              </div>
            </div>
          </div>
          <div v-else class="item-br item-nothing">无</div>
        </template>
        <template slot="usedAmount" slot-scope="text, record">
          <div v-if="record.productItems.length > 0">
            <div v-for="(item, i) in record.productItems" :key="i" class="item-br">
              <div class="item-nothing">
                {{ item.usedAmount || '无' }}
              </div>
            </div>
          </div>
          <div v-else class="item-br item-nothing">无</div>
        </template>
        <template slot="amount" slot-scope="text, record">
          <div class="product-info pl14">
            <div>
              <div>总库存：{{ record.stockAmount }}</div>
              <div>库存状态：{{ record.hasSoldOutStr }}</div>
              <div>实际销量：{{ record.saleAmount }}</div>
            </div>
          </div>
        </template>
        <template slot="saleAmount" slot-scope="text, record">
          <div v-if="record.productItems.length > 0">
            <div v-for="(item, i) in record.productItems" :key="i" class="item-br">
              <div class="item-nothing">
                {{ item.saleAmount }}
              </div>
            </div>
          </div>
          <div v-else class="item-br item-nothing">无</div>
        </template>
        <template slot="refundAmount" slot-scope="text, record">
          <div v-if="record.productItems.length > 0" class="mr14">
            <div v-for="(item, i) in record.productItems" :key="i" class="item-br">
              <div class="item-nothing">
                {{ item.refundAmount || '无' }}
              </div>
            </div>
          </div>
          <div v-else class="item-br item-nothing">无</div>
        </template>
        <template slot="time" slot-scope="text, record">
          <div class="ml14">
            <div>生效：{{ record.validBeginDate || '无' }}</div>
            <div>到期：{{ record.validEndDate || '无' }}</div>
            <div>抢购开始：{{ record.beginTime || '无' }}</div>
            <div>抢购结束：{{ record.endTime || '无' }}</div>
            <div>预计上线：{{ record.estimateReleaseTime || '无' }}</div>
            <div>文案确认：{{ record.editorConfirmDate || '无' }}</div>
            <div>产品经理确认：{{ record.confirmDate || '无' }}</div>
          </div>
        </template>
        <template slot="status" slot-scope="text, record">
          <div class="ml14">
            <!-- ,6:已上架 -->
            <a-tag style="margin-left:8px" v-if="record.productStatus === 6" color="green">
              {{ record.productStatusStr }}
            </a-tag>
            <!-- ,2:已派文案,3:已派设计师,4:待上架确认 -->
            <a-tag style="margin-left:8px" v-if="record.productStatus <= 4 && record.productStatus >= 2" color="blue">
              {{ record.productStatusStr }}
            </a-tag>
            <!-- 1:待派单  7:已下架 -->
            <a-tag style="margin-left:8px" v-if="record.productStatus === 1 || record.productStatus === 7" color="red">
              {{ record.productStatusStr }}
            </a-tag>
            <!--  5:待上架 -->
            <a-tag style="margin-left:8px" v-if="record.productStatus === 5 || record.productStatus == -1" color="orange">
              {{ record.productStatusStr }}
            </a-tag>
            <!-- 0:待完成 -->
            <a-tag style="margin-left:8px" v-else-if="record.productStatus === 0">
              {{ record.productStatusStr }}
            </a-tag>
          </div>
        </template>

        <template slot="stockAmount1" slot-scope="text">
          <div class="ml14">
            {{ text }}
          </div>
        </template>
        <template slot="saleAmount1" slot-scope="text">
          <div class="ml14">
            {{ text }}
          </div>
        </template>
        <template slot="releasedChannels" slot-scope="text">
          <div v-for="(el, index) in text" :key="index">
            {{ el }}
          </div>
        </template>
        <template slot="aciotn" slot-scope="text, record">
          <template v-if="record.productStatus != -1">
            <a-button type="link" @click="goto(record)">编辑 </a-button>
            <a-button type="link" @click="dispatch(record)" v-if="record.productStatus == 2">指派设计师</a-button>
          </template>
          <a-button type="link" @click.stop="viewDetails(record)">详情</a-button>
          <!-- <a-button type="link" @click.stop="orderTransfer(record)" v-if="record.productStatus == 3 || record.productStatus == 4">转单</a-button> -->
          <template v-if="record.productStatus != -1">
            <a-button type="link" @click.stop="copyConfirmation(record)" v-if="record.productStatus == 3">确认文案</a-button>
          </template>
        </template>
      </a-table>
      <div style="text-align: right;font-size:16px">共 {{ total }} 条</div>
    </div>

    <!-- <a-pagination v-model="search.pageIndex" :total="total" show-less-items /> -->
    <a-modal :footer="null" :visible="viewDetailsModal" :width="1100" @cancel="viewDetailsModal = false">
      <template slot="title">
        <span style="font-size:22px;">{{ viewDetailsModalRecord.productTitle }}</span>
        <a-tag style="margin-left:8px" v-if="viewDetailsModalRecord.hasSoldOut === 1" color="orange">
          售罄
        </a-tag>
        <a-tag style="margin-left:8px" v-else-if="viewDetailsModalRecord.hasSoldOut === 0" color="cyan">
          未售罄
        </a-tag>
      </template>
      <div class="detailModalNew">
        <div>
          <title-box>产品基本信息</title-box>
          <div class="top">
            <div>
              <p style="margin-top:20px">产品名称：{{ viewDetailsModalRecord.productName | handleData }}</p>
              <p>产品类型：{{ viewDetailsModalRecord.ecommerceTypeDesc | handleData }}</p>
              <p>产品品类：{{ viewDetailsModalRecord.categoryIdsDesc | handleData }}</p>
              <p>发码设置：{{ viewDetailsModalRecord.codeTypeStr | handleData }}</p>
            </div>
            <div style="width:27%">
              <p class="mt20">需填写收货地址：{{ viewDetailsModalRecord.bookingShowAddress ? '是' : '否' }}</p>
              <p>需填写身份证号：{{ viewDetailsModalRecord.orderShowIdCard ? '是' : '否' }}</p>
              <p>需填写使用日期：{{ viewDetailsModalRecord.orderShowDate ? '是' : '否' }}</p>
              <p>预约方式：{{ viewDetailsModalRecord.bookingTypeStr }}</p>
            </div>
            <div>
              <p style="margin-top:20px">
                产品经理：{{ viewDetailsModalRecord.pmName | handleData }}/{{ viewDetailsModalRecord.pmPhone | handleData }}

                <a-tag v-if="viewDetailsModalRecord.pmStatus === 3">
                  已离职
                </a-tag>
              </p>
              <p>
                文案编辑：{{ viewDetailsModalRecord.editUserName | handleData }}/{{ viewDetailsModalRecord.editPhone | handleData }}
                <a-tag v-if="viewDetailsModalRecord.editStatus === 3">
                  已离职
                </a-tag>
              </p>
              <p>
                设计人员：{{ viewDetailsModalRecord.designer | handleData }}/{{ viewDetailsModalRecord.designerPhone | handleData }}
                <a-tag v-if="viewDetailsModalRecord.designerStatus === 3">
                  已离职
                </a-tag>
              </p>
              <p v-if="viewDetailsModalRecord.aheadBooking">提前几天预约：{{ viewDetailsModalRecord.aheadBooking }}天</p>
            </div>
            <div class="qrcode-box">
              <div class="qrcode" ref="qrCodeUrl"></div>
              <p style="font-size: 12px;">请使用微信扫描二维码预览</p>
            </div>
          </div>

          <title-box>时间</title-box>
          <div class="top">
            <div>
              <p style="margin-top:20px">生效时间：{{ viewDetailsModalRecord.validBeginDate | handleData }}</p>

              <p>到期时间：{{ viewDetailsModalRecord.validEndDate | handleData }}</p>
              <p v-if="viewDetailsModalRecord.delayedValidEndDate">生效延期：{{ viewDetailsModalRecord.delayedValidEndDate | handleData }}</p>
            </div>
            <div style="width:27%">
              <p style="margin-top:20px">抢购开始：{{ viewDetailsModalRecord.beginTime | handleData }}</p>
              <p>抢购结束：{{ viewDetailsModalRecord.endTime }}</p>
              <p style="margin-top:20px" v-if="viewDetailsModalRecord.delayedEndDate">抢购延期：{{ viewDetailsModalRecord.delayedEndDate | handleData }}</p>
            </div>
            <div>
              <p style="margin-top:20px">文案确认：{{ viewDetailsModalRecord.editorConfirmDate | handleData }}</p>
              <p>产品经理确认：{{ viewDetailsModalRecord.confirmDate }}</p>
            </div>
          </div>

          <div>
            <title-box>数量</title-box>
          </div>
          <div class="top mt20 mb14 inlinetop">
            <span>实际库存：{{ viewDetailsModalRecord.stockAmount | handleData }}</span>
            <span>加推库存：{{ viewDetailsModalRecord.addStockAmount | handleData }}</span>

            <span>实际销量：{{ viewDetailsModalRecord.saleAmount | handleData }}</span>

            <span>起始销量：{{ viewDetailsModalRecord.baseAmount | handleData }}</span>
            <span>达人分享数：{{ viewDetailsModalRecord.sharingCount | handleData }}</span>
          </div>

          <div>
            <div>
              <title-box>地址</title-box>
              <p style="margin-top:20px">
                推广地址：<a :href="viewDetailsModalRecord.productUrl">{{ viewDetailsModalRecord.productUrl | handleData }}</a>
                <a-button type="link" @click="onCopy('productUrl')" v-if="viewDetailsModalRecord.productUrl">一键复制</a-button>
                <input v-model="viewDetailsModalRecord.productUrl" style="opacity:0" ref="productUrl" />
              </p>
              <p>
                推文地址：<a :href="viewDetailsModalRecord.pushUrl">{{ viewDetailsModalRecord.pushUrl | handleData }}</a>
                <a-button type="link" @click="onCopy('pushUrl')" v-if="viewDetailsModalRecord.pushUrl">一键复制</a-button>
                <input v-model="viewDetailsModalRecord.pushUrl" style="opacity:0" ref="pushUrl" />
              </p>
            </div>
          </div>
        </div>
      </div>
      <a-table rowKey="id" :loading="initLoading" :columns="innerColumns" :dataSource="productItemDetailList" :pagination="false" v-if="productItemDetailList.length > 0">
        <template slot="number" slot-scope="text, row">
          <div class="flexDiv">
            <div>
              <p v-if="viewDetailsModalRecord.itemStock">套餐库存：{{ row.stockAmount | handleData }}</p>
              <p>发码数：{{ row.codeAmount | handleData }}</p>
              <p>最大购买量：{{ row.singleMax | handleData }}</p>

              <!-- <p>线上留单量：{{ row.onlineReservation | handleData }}</p> -->
              <!-- <p>商家核销量：{{ row.usedAmount | handleData }}</p> -->
              <p>置换数量：{{ row.zeroReplaceAmount || 0 }}</p>
            </div>
            <div>
              <!-- <p v-if="viewDetailsModalRecord.itemStock">剩余库存：{{ row.surplusStocks | handleData }}</p> -->
              <!-- <p>发码数量：{{ row.codeAmount | handleData }}</p> -->
              <!-- <p>线下实际导单量：{{ row.offlineRealSales | handleData }}</p> -->
              <!-- <p>线下留单量：{{ row.offlineReservation | handleData }}</p> -->
              <!-- <p>线下退款量：{{ row.offlineRefundAmount | handleData }}</p> -->
              <!-- <p>商城销量：{{ row.mallSalesWithProduct | handleData }}</p> -->
              <!-- <p>报量：{{ row.forShopsSales }}</p> -->
              <!-- <p>请款量：{{ row.completeAmount | handleData }}</p> -->
            </div>
          </div>
        </template>
        <template slot="price" slot-scope="text, row">
          <div v-if="viewDetailsModalRecord.mainlineChannel && viewDetailsModalRecord.mainlineChannel.length">
            <p>售价：{{ row.salePrice | handleData }}</p>
            <p>原价：{{ row.originPrice | handleData }}</p>
          </div>
          <p>商家结算：{{ row.settlePrice | handleData }}</p>
          <p>渠道结算：{{ row.channelPrice | handleData }}</p>
        </template>
        <template slot="media" slot-scope="text, row">
          <div>
            <div v-if="row.tiktokInfo">
              <p>抖音售价：{{ row.tiktokInfo.salePrice | handleData }}</p>
              <p>抖音原价：{{ row.tiktokInfo.originPrice | handleData }}</p>
            </div>
            <div v-if="row.kuaiShouInfo">
              <p>快手售价：{{ row.kuaiShouInfo.salePrice | handleData }}</p>
              <p>快手原价：{{ row.kuaiShouInfo.originPrice | handleData }}</p>
            </div>
          </div>
        </template>
        <template slot="talentOfSmallYuan" slot-scope="text, row">
          <p v-if="viewDetailsModalRecord.mainlineChannel && viewDetailsModalRecord.mainlineChannel.length">大/小佣金：￥{{ row.superFirstMoney | handleData }}/￥{{ row.secondMoney | handleData }}</p>
          <p v-if="viewDetailsModalRecord.showByteDanceMoneyFlag == 1">抖音佣金： {{ row.byteDanceMoney }}</p>
          <p v-if="row.tiktokInfo">渠道平台佣金（抖音）：{{ row.tiktokInfo.channelMoney }}</p>
          <p v-if="row.kuaiShouInfo">渠道平台佣金（快手）：{{ row.kuaiShouInfo.channelMoney }}</p>
        </template>
        <template slot="channelPrice" slot-scope="text, row">
          <span v-if="viewDetailsModalRecord.itemMoney === 0">{{ (row.sellPriceYuan - viewDetailsModalRecord.talentOfMiddleYuan - viewDetailsModalRecord.talentOfSmallYuan).toFixed(2) }}</span>
          <span v-else>{{ (row.sellPriceYuan - row.talentOfMiddleYuan - row.talentOfSmallYuan).toFixed(2) }} </span>
        </template>
      </a-table>
    </a-modal>
    <a-modal v-model="dispatchVisible" title="指派设计师" @ok="handleDispatchOk" :width="421">
      <div class="pr12">
        选择设计：
        <a-select
          showSearch
          :defaultActiveFirstOption="false"
          :filterOption="false"
          style="width:100%;"
          @search="getAllAssign($event)"
          :notFoundContent="null"
          v-model="dispatchItems.assignId"
          placeholder="请输入搜索并选择指定设计师"
          class="filter-select"
        >
          <a-select-option v-for="item in productAssignList" :key="item.designerId" :value="item.designerId">{{ item.designerName }} </a-select-option>
        </a-select>
      </div>
    </a-modal>
    <a-modal v-model="orderTransferVisible" title="转单" @ok="handleOrderTransferOk" :width="421">
      <div class="pr12">
        选择文案：
        <a-select
          showSearch
          :defaultActiveFirstOption="false"
          :filterOption="false"
          style="width:100%;"
          @search="getAllWriter($event)"
          :notFoundContent="null"
          v-model="dispatchItems.writerId"
          placeholder="请输入搜索并选择指定文案人员"
          class="filter-select"
        >
          <a-select-option v-for="item in productWriterList" :key="item.writerId" :value="item.writerId">{{ item.writerName }} </a-select-option>
        </a-select>
      </div>
    </a-modal>
  </div>
</template>

<script>
import titleBox from '../goodsManag/components/detailsTitle'
import QRCode from 'qrcodejs2'
import {
  getProductWriterList,
  getShareUrl,
  companyWithUser,
  getAllStationNew,
  getProductInfo,
  getProductWriter,
  getProductSaleList,
  setProductAssignPaperwork,
  getProductAssignList,
  setProductAssignDesigner,
  setProductAssignConfirm
} from '@/service'
import { mscf } from '@/util'
import { dateFormat } from 'nearby-common'
import debounce from 'lodash/debounce'
const columns = [
  {
    title: '站点',
    dataIndex: 'locationName',
    key: 'locationName',
    width: 75,
    scopedSlots: { customRender: 'locationName' }
  },
  {
    title: '产品信息',
    dataIndex: 'productName',
    key: 'productName',
    width: 260,
    scopedSlots: { customRender: 'name' }
  },

  {
    title: '人员',
    dataIndex: 'pmName',
    key: 'pmName',
    width: 280,
    scopedSlots: { customRender: 'pmName' }
  },
  {
    title: '合同',
    dataIndex: 'contractName',
    key: 'productTitle',
    width: 200,
    scopedSlots: { customRender: 'contractName' }
  },
  {
    title: '套餐名称',
    dataIndex: 'productItems',
    key: 'subTitle',
    width: 200,
    scopedSlots: { customRender: 'subTitle' }
  },

  {
    title: '佣金',
    dataIndex: 'productItems',
    key: 'superFirstMoney',
    width: 140,
    scopedSlots: { customRender: 'superFirstMoney' }
  },
  {
    title: '价格(元)',
    dataIndex: 'productItems',
    key: 'salePrice',
    width: 150,
    scopedSlots: { customRender: 'salePrice' }
  },
  {
    title: '数量',
    dataIndex: 'productItems',
    key: 'stockAmount',
    width: 180,
    scopedSlots: { customRender: 'amount' }
  },

  {
    title: '时间',
    dataIndex: 'releaseTime',
    key: 'releaseTime',
    width: 268,
    scopedSlots: { customRender: 'time' }
  },
  {
    title: '状态',
    dataIndex: 'statusDesc',
    key: 'statusDesc',
    width: 100,
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '上架渠道',
    dataIndex: 'releasedChannels',
    key: 'releasedChannels',
    width: 100,
    scopedSlots: { customRender: 'releasedChannels' }
  },
  {
    title: '操作',
    dataIndex: 'aciotn',
    key: 'aciotn',
    fixed: 'right',
    width: 100,
    scopedSlots: { customRender: 'aciotn' }
  }
]
const cannactColumns = [
  {
    title: '合同名称',
    dataIndex: 'contractName',
    key: 'contractName'
    // scopedSlots: { customRender: 'name' }
  },
  {
    title: '合同类型',
    dataIndex: 'contractType',
    key: 'contractType'
    // scopedSlots: { customRender: 'name' }
  },
  {
    title: '产品经理',
    dataIndex: 'pmUserName',
    key: 'pmUserName'
    // scopedSlots: { customRender: 'name' }
  },
  {
    title: '创建时间',
    dataIndex: 'createDate',
    key: 'createDate'
    // scopedSlots: { customRender: 'name' }
  }
]

const detailsSalesColumns = [
  {
    title: '上线站点',
    dataIndex: 'locationName',
    key: 'locationName'
  },
  {
    title: '套餐',
    dataIndex: 'productItemName',
    key: 'productItemName'
  },
  {
    title: '实际销量',
    dataIndex: 'saleOrderAmount',
    key: 'saleOrderAmount'
  },
  {
    title: '核销量',
    dataIndex: 'usedAmount',
    key: 'usedAmount'
  },
  {
    title: '退款量',
    dataIndex: 'refundOrderAmount',
    key: 'refundOrderAmount'
  }
]
export default {
  name: 'copywritingList',
  components: { titleBox },
  // 节流

  data() {
    this.getAllStation = debounce(this.getAllStation, 800)
    this.getAllWriter = debounce(this.getAllWriter, 800)
    return {
      total: 0,
      orderTransferVisible: false,
      cannactId: null,
      cannactName: null,
      productAssignList: [],
      productWriterList: [],
      contractNameId: null,
      allCannact: [],
      cannactDataList: [],
      detailsSalesList: [],
      detailsSalesColumns,
      dispatchVisible: false,
      cannactColumns,
      expandedRowKeys: [],
      visible: false,
      allStation: [],
      loading: false,
      viewDetailsModal: false,
      viewDetailsModalRecord: {},
      // 查PM所属公司
      pmCompanyName: undefined,
      // 详情二维码url
      detailUrl: '',
      id: null,
      checkedList: [],
      selectLocationIdList: [],
      spinning: false,
      nationalModal: false,
      columns,
      dateFormat,
      data: [],
      search: {
        locationId: null,
        productType: null,
        keywords: null,
        productStatus: null,
        pageIndex: 1,
        pageSize: 10,
        onlineChannel: null
      },
      pagination: {},
      productItemDetailList: [],
      viewDetailsUrl: '',
      viewPushUrl: '',
      initLoading: false,
      innerColumns: [
        {
          title: '套餐名称',
          width: 140,
          dataIndex: 'subTitle',
          customRender: (text) => {
            if (text) {
              return text
            } else {
              return '无'
            }
          }
        },
        {
          title: '数量',
          width: 180,
          dataIndex: 'singleMax',

          scopedSlots: {
            customRender: 'number'
          }
        },
        {
          title: '价格',
          width: 140,
          dataIndex: 'price',
          scopedSlots: {
            customRender: 'price'
          }
        },
        {
          title: '新媒体渠道价格',
          width: 140,
          dataIndex: 'media',
          scopedSlots: {
            customRender: 'media'
          }
        },
        {
          title: '达人佣金',
          width: 170,
          dataIndex: 'firstMoney',
          scopedSlots: {
            customRender: 'talentOfSmallYuan'
          }
        }
      ],
      productWriterId: null,
      dispatchItems: { bindType: 1 },
      productTitle: '销售详情',
      detailsSalesVisible: false
    }
  },
  created() {
    this.init(this.search)
  },
  methods: {
    async init(search) {
      this.loading = true
      let data = await getProductWriterList(search)
      this.data = data.data
      let { rowCount, pageIndex } = data
      this.pagination = {
        ...this.pagination,
        current: pageIndex,
        total: rowCount
      }
      this.total = rowCount
      this.loading = false
      // console.log(this.pagination)s
    },
    handleChange() {
      this.handlesearch(this.search)
    },
    handlesearch() {
      this.init({ ...this.search, pageIndex: 1, pageSize: 10 })
    },
    reset() {
      this.search = {
        ...this.search,
        locationId: null,
        productType: null,
        keywords: null,
        productStatus: null,
        pageIndex: 1,
        pageSize: 10,
        onlineChannel: null
      }
      this.init(this.search)
    },
    paginationChange(pagination) {
      console.log(pagination)
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.search.pageIndex = pagination.current
      this.init(this.search)
    },
    goto(record) {
      let id = record ? record.id : null
      mscf.emit('openNewSystem', '*', {
        target: 'product',
        page: 'newOrder',
        params: {},
        query: {
          id: id,
          contractId: record.contractId,
          activeKey: 6,
          admin: 4, // 产品1 （前5个） 单上抖音 2（前6个 只有一个附件图片） 文案/设计 0（后两个） 超管3 所有
          breadCrumbs: this.$route.matched[this.$route.matched.length - 1].path,
          _r: (Math.random() * 100).toFixed(0)
        }
      })
    },
    creatQrCode(text) {
      if (this.$refs.qrCodeUrl.childNodes.length) {
        let el = this.$refs.qrCodeUrl
        let childs = el.childNodes
        for (let i = childs.length - 1; i >= 0; i--) {
          el.removeChild(childs[i])
        }
      }

      let qrcode = new QRCode(this.$refs.qrCodeUrl, {
        text: text, // 需要转换为二维码的内容
        width: 145,
        height: 145,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
      })
      console.log(qrcode)
    },
    expand(record) {
      // this.productId = record.id
      this.productItemDetailList = []
      // this.expandedRowKeys = expanded ? [record.id] : []
      this.initLoading = true
      getProductInfo({
        id: record.id
      })
        .then((res) => {
          this.productItemDetailList = res.itemsInfo.items
          this.viewDetailsModalRecord = {
            ...res.baseInfo,
            ...res.bookingAndCodeInfo,
            ...res.itemsInfo
          }
        })
        .finally(() => {
          this.initLoading = false
        })
    },
    viewDetails(record) {
      this.expand(record)
      getShareUrl({ productId: record.id }).then((res) => {
        this.creatQrCode(res.url)
        this.viewDetailsUrl = res.url
        this.viewPushUrl = res.pushUrl
      })
      companyWithUser({ userId: record.pmUserId }).then((res) => {
        if (res.length) {
          this.pmCompanyName = res[0].name
        }
      })
      this.viewDetailsModal = true
    },

    getAllStation(e) {
      if (!e) return false
      getAllStationNew({ keywords: e }).then((res) => {
        this.allStation = res
      })
    },
    // 站点变更事件
    changeSite(value) {
      this.search.locationId = value
      this.addForm.locationId = value
      for (let o in this.allStation) {
        if (Number(this.allStation[o].id) === Number(value)) {
          this.locationName = this.allStation[o].city
        }
      }
      this.init()
    },
    dispatch(v) {
      this.dispatchVisible = true
      this.productWriterId = v.id
    },
    orderTransfer(v) {
      this.orderTransferVisible = true
      this.productWriterId = v.id
    },
    async handleOrderTransferOk() {
      await setProductAssignPaperwork({
        paperworkId: this.dispatchItems.writerId,
        productId: this.productWriterId
      })
      this.$messageSend.success('转单成功！')
      this.init(this.search)
      this.dispatchItems = { bindType: 1 }
      this.orderTransferVisible = false
    },
    async getAllWriter(v) {
      if (!v) return false
      let data = await getProductWriter({
        writerName: v,
        productId: this.productWriterId
      })
      console.log(data)
      this.productWriterList = data
    },
    async getAllAssign(v) {
      if (!v) return false
      let data = await getProductAssignList({
        name: v,
        productId: this.productWriterId
      })
      this.productAssignList = data
    },
    async handleDispatchOk() {
      console.log(this.dispatchItems)
      await setProductAssignDesigner({
        productId: this.productWriterId,
        designerId: this.dispatchItems.assignId
      })
      this.$messageSend.success('指派成功！')
      this.init(this.search)
      this.dispatchItems = { bindType: 1 }
      this.dispatchVisible = false
    },
    async viewSalesDetails(v) {
      this.pagination = {}
      this.productTitle = v.productName
      this.productWriterId = v.id
      let data = await getProductSaleList({
        id: v.id
      })
      this.pagination = {
        ...this.pagination,
        total: data.rowCount
      }
      this.detailsSalesList = data.data
      this.detailsSalesVisible = true
    },
    async paginationSalesDetailsChange(pagination) {
      console.log(pagination)
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      let pageIndex = pagination.current

      let data = await getProductSaleList({
        id: this.productWriterId,
        pageIndex
      })
      this.pagination = {
        ...this.pagination,
        total: data.rowCount
      }
      this.detailsSalesList = data.data
    },
    copyConfirmation({ id }) {
      let dataJson = {
        productId: id
      }
      this.$confirm({
        title: `确认文案会检查产品是否能上线，发布的配置参数是否准备好，您确认现在要确认文案吗？`,
        // content: (h) => <div style="color:red">{this.viewDetailsModalRecord.name}</div>,
        onOk: () => {
          setProductAssignConfirm(dataJson).then((res) => {
            this.$messageSend.success('操作成功!')
            this.init(this.search)
          })
        }
      })
    },
    onCopy(key) {
      this.$refs[key].select()
      document.execCommand('Copy')
      this.$messageSend.success('复制成功')
    }
  }
}
</script>

<style lang="less" scoped>
.copywritingList {
  height: 100%;
  // overflow: auto;
  // margin-bottom: 10px;

  background: #fff;
  padding: 10px 14px 0 20px;
  .title {
    // width: 100%;
    display: flex;
    // text-align: center;
    align-items: center;
    height: 64px;
    .title-left {
      font-size: 18px;
      color: #333333;
      font-weight: 500;
    }
    .title-btn {
      flex: 1;
      text-align: right;
    }
  }
  .search-box-new {
    height: 50px;
    background: #fafafa;
    border-radius: 2px;
    border: 1px solid #f0f0f0;
    padding: 0 14px;
    display: flex;
    align-items: center;
    .search-box-btn {
      flex: 1;
      text-align: right;
    }
  }
  .item-br {
    border-bottom: 1px solid #f0f0f0;
    padding: 0px 0 0px 14px;
    margin-top: 5px;
    // line-height: 75px;
    height: 110px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    // padding-left: 10px;
  }
  .item-br:last-child {
    border-bottom: none;
  }
  .item-no-pl {
    padding-left: 0;
  }
  .del-line {
    text-decoration: line-through;
  }
  .item-nothing {
    margin-top: 0;
    line-height: 75px;
    word-break: break-all;
    text-overflow: ellipsis;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    // z-index: 9999;
    // word-wrap: break-word;
    // word-break: break-all;
  }
  .product-info {
    display: flex;
    align-items: center;
    img {
      width: 80px;
      height: 80px;
      border-radius: 8px;
      background-size: contain;
    }
  }
  .qrcode-box {
    position: absolute;
    top: 0;
    right: 0;
    width: 120px !important;
    height: 120px !important;
  }
  .qrcode {
    display: inline-block;
    width: 120px !important;
    height: 120px !important;
    font-size: 12px;
    img {
      width: 120px !important;
      height: 120px !important;
      background-color: #fff; //设置白色背景色
      padding: 6px; // 利用padding的特性，挤出白边
      box-sizing: border-box;
    }
    canvas {
      width: 120px !important;
      height: 120px !important;
    }
  }
  .detailModalNew {
    position: relative;
    .top {
      display: flex;
      width: 100%;
      // justify-content: space-between;
      div {
        width: 33.33%;
      }
      // div:nth-of-type(2) {
      //   margin-left: 120px;
      // }
    }
    .inlinetop {
      padding-right: 145px;
      justify-content: space-between;
    }
  }
}
</style>
<style lang="scss">
.copywritingList {
  .main-body {
    height: 100%;
    .ant-table {
      .ant-table-content {
        .ant-table-body,
        .ant-table-fixed-right {
          table > .ant-table-tbody > tr > td {
            padding: 3px 0 !important;
            color: #333333;
          }
        }
      }
    }
  }
  .main-body .ant-table-thead .ant-table-row-cell-break-word {
    background: none;
  }
  .qrcode {
    display: inline-block;
    width: 120px !important;
    height: 120px !important;

    img {
      width: 120px !important;
      height: 120px !important;
      background-color: #fff; //设置白色背景色
      padding: 6px; // 利用padding的特性，挤出白边

      box-sizing: border-box;
    }
    canvas {
      width: 120px !important;
      height: 120px !important;
    }
  }
}
.productIndex {
  .main-body {
    .ant-table-thead > tr > th {
      padding: 14px;
    }
  }
}
</style>
